package com.nenglai.common.validator;

import lombok.SneakyThrows;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

public class CompareDoubleValidator implements ConstraintValidator<CompareDouble, Object> {

    private String value1;
    private String value2;

    public void initialize(CompareDouble constraintAnnotation) {
        this.value1 = constraintAnnotation.value1();
        this.value2 = constraintAnnotation.value2();
    }

    @SneakyThrows
    public boolean isValid(Object obj, ConstraintValidatorContext constraintValidatorContext) {

        Class<?> aClass = obj.getClass();
        Field field1 = aClass.getDeclaredField(this.value1);
        field1.setAccessible(true);
        Object o1 = field1.get(obj);

        Field field2 = aClass.getDeclaredField(this.value2);
        field2.setAccessible(true);
        Object o2 = field2.get(obj);

        return o1.equals(o2);
    }

}
